package com.zhoug.widget.round;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;

import com.zhoug.widget.R;

import androidx.appcompat.widget.AppCompatImageView;

/**
 * 圆角图片组件
 */
public class RoundImageView extends AppCompatImageView {
    private static final String TAG = ">>>RoundImageView";
    private RoundHelper roundHelper;
    private boolean roundEnable;
    private int borderWidth;
    private int borderColor;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        roundEnable = typedArray.getBoolean(R.styleable.RoundImageView_roundEnabled, true);
        int corners = typedArray.getDimensionPixelSize(R.styleable.RoundImageView_corners, 10);
        boolean circular = typedArray.getBoolean(R.styleable.RoundImageView_circular, false);
        borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundImageView_border_Width, 0);
        borderColor = typedArray.getColor(R.styleable.RoundImageView_border_Color, Color.parseColor("#555555"));

        typedArray.recycle();
        setScaleType(ScaleType.CENTER_CROP);
        roundHelper = new RoundHelper(corners, circular);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        roundHelper.onSizeChanged(getWidth(), getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (roundEnable) {
            roundHelper.clipRound(canvas);
        }
        super.onDraw(canvas);
        if (roundEnable) {
            roundHelper.drawBorder(canvas,borderWidth,borderColor);
        }
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        super.setScaleType(ScaleType.CENTER_CROP);
    }

    public int getCorners() {
        return roundHelper.getCorners();
    }

    public void setCorners(int corners) {
        roundHelper.setCorners(corners);
    }

    public boolean isCircular() {
        return roundHelper.isCircular();
    }

    public void setCircular(boolean circular) {
        roundHelper.setCircular(circular);
    }


}
